import React, { Component } from "react";
import Nav from "./navbar";
import ListPage from "./listPage";
import ItemA from "../hoc/itemA";
import ItemB from "../hoc/itemB";
import ItemC from "../rp/itemC";

class Cart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listData: [
        {
          id: 1,
          name: "戴尔 G3游戏本",
          price: 5399.0,
          stock: 11,
        },
        {
          id: 2,
          name: "华为 hour商务本",
          price: 7299.0,
          stock: 11,
        },
        {
          id: 3,
          name: "苹果 11pro开发本",
          price: 5399.0,
          stock: 11,
        },
      ],
    };
  }

  handleDelete = (id) => {
    const _list = this.state.listData.filter((item) => item.id !== id);
    this.setState({
      listData: _list,
    });
  };

  handleReset = () => {
    const _list = this.state.listData.map((item) => {
      const _item = { ...item };
      _item.stock = 0;
      return _item;
    });
    this.setState({
      listData: _list,
    });
  };

  handleMinus = (id) => {
    const _data = this.state.listData.map((item) => {
      if (item.id === id) {
        const _item = { ...item };
        _item.stock--;
        if (_item.stock < 0) _item.stock = 0;
        return _item;
      } else {
        return item;
      }
    });
    this.setState({
      listData: _data,
    });
  };
  handlePlus = (id) => {
    const _data = this.state.listData.map((item) => {
      if (item.id === id) {
        const _item = { ...item };
        _item.stock++;
        return _item;
      } else {
        return item;
      }
    });
    this.setState({
      listData: _data,
    });
  };

  handleCountSum = () => {
    let countSum = this.state.listData.reduce((pre, cur) => {
      pre += cur.stock;
      return pre;
    }, 0);
    return countSum;
  };

  render() {
    return (
      <>
        <Nav onReset={this.handleReset} itemNum={this.handleCountSum()} />
        <div className="container">
          <ListPage
            listData={this.state.listData}
            handleDelete={this.handleDelete}
            handleMinus={this.handleMinus}
            handlePlus={this.handlePlus}
          />
        </div>
      </>
    );
  }
}

export default Cart;
